<?php

namespace App\Models;

use App\Http\Controllers\Postalapi\Postal;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/**
 * 书店书籍采购表
 * Class BookHomePurchaseModel
 * @package app\common\model
 */
class BookHomePostalRev extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    protected $table = "book_home_postal_rev";



    /**
     * 获取运单轨迹
     * @param trace_no 运单号
     */
    public function _getTrack($trace_no)
    {

        $res = $this->where('trace_no', $trace_no)
            ->select('trace_content')
            ->orderByDesc('id')
            ->get()
            ->toArray();

        foreach ($res as $key => $val) {
            $trace_content = json_decode($val['trace_content'], true);
            $res[$key] = $trace_content[0];
        }

        return $res ? $res : null;
    }

    /**
     * 获取运单轨迹  (现在改为自己获取)
     * @param trace_no 运单号
     */
    public function getTrack($trace_no)
    {
        $data = Cache::get($trace_no . 'track');
        if ($data) {
            return $data;
        }
        $postalObj = new Postal();
        $data = $postalObj->travel(null, $trace_no);
        if ($data['code'] != 200) {
            return null;
        }
        $data['data'] = array_reverse($data['data']);

        Cache::put($trace_no . 'track', $data['data'], 300);
        return $data['data'];
    }
}
